<?php

/**
 * user actions.
 *
 * @package    Amman to London
 * @subpackage user
 * @author     Adel Abu-Saif <adeljas@msn.com>
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userActions extends sfActions {

    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */
    public function executeIndex(sfWebRequest $request) {
        $this->forward('default', 'module');
    }

    public function executeRegister($request) {
        $this->form = new sfGuardRegisterForm();
        $this->form->getValidator('first_name')->setOption('required', true);
        unset($this->form['last_name']);
        if ($request->isMethod('POST')) {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid()) {
                $this->form->save();
                $this->setTemplate('register_success');
            } else {
                //  die($this->form);
            }
        }
    }

    public function executeAutocompleteUniversity(sfWebRequest $request) {

        $culture = $this->getUser()->getCulture();

        if ($culture == "en") {
            $result = Doctrine_Core::getTable('University')
                    ->findUniversityByName($request['q'])
                    ->toKeyValueArray('id', 'name_en');
        } else {
            $result = Doctrine_Core::getTable('University')
                    ->findUniversityByNameAR($request['q'])
                    ->toKeyValueArray('id', 'name_ar');
        }
        return $this->renderText(json_encode($result));
    }

    public function executeAutocompleteFaculty(sfWebRequest $request) {


        if ($request['q']) {

            $culture = $this->getUser()->getCulture();

            if ($culture == "en") {
                $result = Doctrine_Core::getTable('Faculty')
                        ->findFacultyByName($request['q'], 10, $request['uni_id'])
                        ->toKeyValueArray('id', 'name_en');
            } else {

                $result = Doctrine_Core::getTable('Faculty')
                        ->findFacultyByNameAR($request['q'], 10, $request['uni_id'])
                        ->toKeyValueArray('id', 'name_ar');
            }
            return $this->renderText(json_encode($result));
        } else {
            return $this->renderText("select Faculty");
        }
    }

    public function executeFacebook_logged_in($request) {
        $this->app_id = sfConfig::get('app_facebook_app_id');
        $this->setLayout('none');
    }

    public function executeActivate($request) {
        $token = $request->getParameter('token', false);
        if ($token === false)
            exit;

        $obj = sfGuardUserTable::getInstance()->createQuery()->where('salt = ?', $token)->fetchOne();
        if (!is_object($obj))
            die('!! invalid security token !!');

        $obj->set('is_active', true);
        $obj->save();
        $this->getUser()->signin($obj);
    }

    public function executePersonal_info($request) {
        $user_id = $this->getUser()->getGuardUser()->getId();
        $this->form = new sfGuardRegisterForm($this->getUser()->getGuardUser());
        $this->form->getValidator('first_name')->setOption('required', true);
        unset($this->form['password']);
        unset($this->form['first_name']);
        unset($this->form['email_address']);
        unset($this->form['username']);
        $fq = FacultyTable::getInstance()
                ->createQuery('r')
                ->where('university_id = ?', $this->getUser()->getGuardUser()->getUniversityId());
        // $this->form->getWidget('faculty_id')->setOption('query', $fq);
        if ($request->isMethod('POST')) {
            $values = $request->getParameter($this->form->getName());
            if ($values['faculty_id'] != $this->form->getObject()->get('faculty_id')) {
                UserDosTable::getInstance()->createQuery()->where('user_id = ?', $user_id)->delete()->execute();
            }
            $this->form->bind($values);
            if ($this->form->isValid()) {
                $obj = $this->form->save();
                $this->getUser()->setFlash('notice', 'Personal Info Saved Successfully');
                $this->redirect('user/my_doseyeh');
            } else {
                //echo $this->form;
            }
        }

        $upload = new sfForm();
        $upload->setWidget('file', new sfWidgetFormInputFile());
        $upload->setValidator('file', new sfValidatorFile(array('path' => sfConfig::get('sf_upload_dir') . '/profile_pictures/')));
        $this->picture_form = $upload;
        $this->picture_form->getWidgetSchema()->setNameFormat('profile_picture[%s]');
    }

    public function executePreview($request) {

        $culture = $this->getUser()->getCulture();
        $enrolled_courses = UserDosTable::getInstance()
                ->createQuery("ud")
                ->where('user_id = ?', $this->getUser()->getGuardUser()->getId())
                ->leftJoin("ud.Course c")
                ->select('ud.course_id,c.name_' . $culture . ' as course_name')
                ->fetchArray();

        $enrolled_arr = array();
        $this->arr = array();

        foreach ($enrolled_courses as $one) {
            $enrolled_arr[] = $one['course_id'];
        }



        foreach ($enrolled_courses as $course) {


            $this->arr[$course['course_name']] = DosTable::getInstance()
                    ->createQuery('d')
                    ->leftJoin('d.Course c')
                    ->select('c.id,d.id, d.rating, cover_image, name_' . $culture . ' as dos_name, c.name_' . $culture . ' as course_name')
                    ->where('d.course_id = ?', $course['course_id'])
                    ->fetchArray();
        }

//        echo "<pre>";
//        print_r($this->arr);
//        die();
    }

    public function executeMy_doseyeh($request) {

        $user_id = $this->getUser()->getGuardUser()->getId();

        sfContext::getInstance()->getConfiguration()->loadHelpers(array('I18N'));

        if ($request->isMethod(sfWebRequest::POST)) {


            $courses = $request->getParameter('user_dos', false);
            // $instructors = $request->getParameter('instructor', false);

            UserDosTable::getInstance()->createQuery()->delete()->where('user_id = ?', $user_id)->execute();
            $entered_courses = array();
            $sub = 8;
            if (count($courses) > 0) {
                // charge the user
                $sc_obj = UserBalanceTable::getInstance()->findOneBy('user_id', $user_id);
                if (is_object($sc_obj)) {
                    $balance = $sc_obj->get('balance');
                    if ($balance >= 8) {
                        $sc_obj->set('balance', $balance - $sub);
                        $sc_obj->save();

                        foreach ($courses as $k => $one) {
                            if ($one == '' || in_array($one, $entered_courses))
                                continue;
                            $obj = new UserDos();
                            $obj->set('user_id', $user_id);
                            $obj->set('course_id', $one);
                            $obj->save();
                            $entered_courses[] = $one;
                        }
                        $this->getUser()->setFlash('notice', __('Successfully added your courses, you have been charged') . ' ' . $sub . __('JDs.'));
                        $this->redirect('user/preview');
                    } else {
                        $this->getUser()->setFlash('error', __('Insufficient balance, you have to add') . ' ' . $sub . __('JDs.'));
                    }
                } else {
                    $this->getUser()->setFlash('error', __('Insufficient balance, you have to add') . ' ' . $sub . __('JDs.'));
                }
            }
        }

        $current_courses_q = UserDosTable::getInstance()
                ->createQuery()
                ->select('id, course_id, instructor_id')
                ->where("user_id = ?", $user_id);
        $this->current_courses = $current_courses_q->fetchArray();

        $cc_count = $current_courses_q->count();

        $course_instructor = array();

        $culture = $this->getUser()->getCulture();

        foreach ($this->current_courses as $one) {
            $data = InstructorTable::getInstance()
                    ->createQuery('i')
                    ->select('i.id, i.name_' . $culture . ' as name')
                    ->innerJoin('i.CourseFaculty cf')
                    ->where('cf.course_id = ?', $one['course_id'])
                    ->fetchArray();
            $course_instructor[$one['course_id']] = $data;
        }

        $this->course_instructor = $course_instructor;

        $this->disable_form = $cc_count > 0;
    }

    public function executeAutocompleteMyDoseyeh(sfWebRequest $request) {

        if ($request['q']) {

            $culture = $this->getUser()->getCulture();
            $user_university_id = $this->getUser()->getGuardUser()->getUniversityId();
            if ($culture == "en") {
                $result = Doctrine_Core::getTable('Course')
                        ->findCourseByName($request['q'], 8, $user_university_id)
                        ->toKeyValueArray('id', 'name_en');
            } else {

                $result = Doctrine_Core::getTable('Course')
                        ->findCourseByNameAR($request['q'], 8, $user_university_id)
                        ->toKeyValueArray('id', 'name_ar');
            }
            return $this->renderText(json_encode($result));
        } else {
            return $this->renderText("select Course");
        }
    }

    public function executeMy_balance($request) {
        $this->error = false;

        $user_id = $this->getUser()->getGuardUser()->getId();
        if ($request->isMethod('POST')) {
            //@todo: check for referer
            $scnum = $request->getParameter('scnum', false);
            $scnum = trim($scnum);
            if ($scnum == '') {
                $this->message = 'please enter your scratch card number';
                $this->error = true;
            }

            if ($this->error === false && !is_numeric($scnum)) {
                $this->message = 'invalid card number';
                $this->error = true;
            }

            if ($this->error === false && strlen($scnum) != 14) {
                $this->message = 'card number should have 14 digits';
                $this->error = true;
            }
            $attempt = $this->getUser()->getAttribute('sc_attempt');
            if ($attempt > 3) {
                $this->message = 'you have been temporarely blocked due to several unsuccessful attempts';
                $this->error = true;
            }

            if ($this->error === false) {
                $q = ScratchCardTable::getInstance()->createQuery()
                        ->where('card_number = ?', $scnum)
                        ->andWhere('is_deleted = ?', 0);
                $count = $q->count();
                if ($count === 0) {
                    if (!is_numeric($attempt))
                        $attempt = 1;
                    //$this->message = 'card number not found, attempt #' . $attempt;
                    $this->message = 'card number not found';
                    $attempt = $this->getUser()->setAttribute('sc_attempt', $attempt + 1);
                    $this->error = true;
                } else {
                    $card = $q->fetchOne();
                    $value = $card->get('value');

                    $q2 = UserBalanceTable::getInstance()->createQuery()->where('user_id = ?', $user_id);

                    $q2count = $q2->count();

                    if ($q2count === 0) {
                        $bobj = new UserBalance();
                        $bobj->set('user_id', $user_id);
                        $bobj->set('balance', $value);
                        $bobj->set('units', ScratchCardTable::$map_value_units[$value]);
                        $bobj->save();
                    } else {
                        $bobj = $q2->fetchOne();
                        $current_value = $bobj->get('balance');
                        $current_units = $bobj->get('units');
                        $charged_value = $value;
                        $charged_units = ScratchCardTable::$map_value_units[$value];
                        $bobj->set('balance', $current_value + $charged_value);
                        $bobj->set('units', $current_units + $charged_units);
                        $bobj->save();
                    }
                    sfContext::getInstance()->getConfiguration()->loadHelpers(array('I18N'));

                    $this->message = __('You have successfully charged') . ' ' . $value . ' JD' . ($value > 1 ? 's' : '');
                    $card->set('is_deleted', 1);
                    $card->set('charged_at', date('Y-m-d H:i:s', time()));
                    $card->save();
                    //$card->delete();
                }
            }
        }

        // get current balance

        $q3 = UserBalanceTable::getInstance()->createQuery()->where('user_id = ?', $user_id);

        $q3count = $q3->count();

        if ($q3count === 0) {
            $this->balance = '0.00';
        } else {
            $bobj = $q3->fetchOne();
            $this->balance = $bobj->get('balance');
        }
    }

    public function executeProfile_picture($request) {
        $this->username = $this->getUser()->getGuardUser()->getUsername();
        $this->setLayout('iframe');
        header("Cache-Control: no-cache, must-revalidate");
        header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
    }

    public function executeRate_dos($request) {
        /* @var $dos_obj Dos */
        $did = $request->getParameter('did', false);
        $rate = $request->getParameter('rate', false);
        $user_id = $this->getUser()->getGuardUser()->getId();
        $rated_before = RateHistoryTable::getInstance()->rated_before('doseyeh', $user_id, $did);
        $dos_obj = DosTable::getInstance()->find($did);
        $current_rating = $dos_obj->getRating();
        if ($rated_before === true)
            return $this->renderText($current_rating);
        $rating_count = $dos_obj->getTimesRated();
        $new_rating = (($current_rating * $rating_count) + $rate ) / ($rating_count + 1);
        $dos_obj->setRating($new_rating);
        $dos_obj->setTimesRated($rating_count + 1);
        $dos_obj->save();
        $rh = new RateHistory();
        $rh->set('model', 'doseyeh');
        $rh->set('user_id', $user_id);
        $rh->set('model_id', $did);
        $rh->save();
        return $this->renderText($new_rating);
        exit;
    }

    public function executeUpload_picture($request) {
        $this->username = $this->getUser()->getGuardUser()->getUsername();
        $upload = new sfForm();
        $upload->setWidget('file', new sfWidgetFormInputFile());
        $upload->setValidator('file', new sfValidatorFile(array('path' => sfConfig::get('sf_upload_dir') . '/profile_pictures/')));
        $this->form = $upload;
        $this->form->getWidgetSchema()->setNameFormat('profile_picture[%s]');
        if ($request->isMethod('POST')) {
            $this->form->bind($request->getParameter($this->form->getName()), $request->getFiles($this->form->getName()));
            if ($this->form->isValid()) {
                $file = $request->getFiles($this->form->getName());
                move_uploaded_file($file['file']['tmp_name'], sfConfig::get('sf_upload_dir') . '/profile_pictures/' . $this->username . '.jpg');
                copy(sfConfig::get('sf_upload_dir') . '/profile_pictures/' . $this->username . '.jpg', sfConfig::get('sf_upload_dir') . '/profile_pictures/' . $this->username . '_thumb.jpg');
                exec('rm ' . sfConfig::get('sf_upload_dir') . '/profile_pictures/thumbs/' . '*' . $this->username . '_thumb.jpg');
                exec('erase ' . sfConfig::get('sf_upload_dir') . '\\profile_pictures\\thumbs\\' . '*' . $this->username . '_thumb.jpg');
            } else {
                die('something went wrong...');
            }
        }

        $this->setTemplate('profile_picture');
        $this->setLayout('iframe');
        header("Cache-Control: no-cache, must-revalidate");
        header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
    }

    public function executeGet_instructors_for_course($request) {
        $course_id = $request->getParameter('id', false);
        if ($course_id === false)
            exit;

        $culture = $this->getUser()->getCulture();

        $data = InstructorTable::getInstance()
                ->createQuery('i')
                ->select('i.id, i.name_' . $culture . ' as name')
                ->innerJoin('i.CourseFaculty cf')
                ->where('cf.course_id = ?', $course_id)
                ->fetchArray();

        $count = count($data);
        if ($count > 0)
            $empty_text = '- Select Instructor -';
        else
            $empty_text = '- no instructors found for this course -';
        return $this->renderPartial('main/options2', array('empty_text' => $empty_text, 'items' => $data, 'count' => $count, 'key_key' => 'id', 'value_key' => 'name'));
    }

    public function executeGet_doseyeh_for_instructor($request) {
        $instructor_id = $request->getParameter('id', false);
        if ($instructor_id === false)
            exit;

        $culture = $this->getUser()->getCulture();

        $data = DosTable::getInstance()
                ->createQuery('i')
                ->select('i.id, i.name_' . $culture . ' as name')
                ->innerJoin('i.CourseFaculty cf')
                ->where('i.instructor_id', $instructor_id)
                ->fetchArray();

        $count = count($data);
        if ($count > 0)
            $empty_text = '- Select Doseyeh -';
        else
            $empty_text = '- no Doseyeh found for this instructor -';
        return $this->renderPartial('main/options2', array('empty_text' => $empty_text, 'items' => $data, 'count' => $count, 'key_key' => 'id', 'value_key' => 'name'));
    }

    public function executeSuggested($request) {
        
    }

    public function executeFreeDosyehPreview($request) {

        $user_faculty = sfguarduserTable::getInstance()
                ->createQuery()
                ->where('id = ?', $this->getUser()->getGuardUser()->getId())
                ->select('faculty_id')
                ->fetchArray();

//        var_dump($this->getUser()->getCulture());exit;
        $culture = $this->getUser()->getCulture() ? $this->getUser()->getCulture() : 'en';
        //    var_dump($culture);exit;
        if (count($user_faculty) > 0) {

            $this->arr = DosTable::getInstance()
                    ->createQuery('d')
                    ->leftJoin('d.Course c')
                    ->select('c.id,d.id, d.rating, cover_image, name_' . $culture . ' as dos_name, c.name_' . $culture . ' as course_name')
                    ->where('d.is_free', 1)
                    ->fetchArray();
//die('sda');        
            //var_dump($this->arr);exit;
        }
    }

    public function executeReq_password(sfWebRequest $request) {


          $this->message = $request->getParameter('message', false);
         $this->form = new sfGuardFormSignin();
        if ($request->isMethod('post')) {
            $username = $request->getParameter('username');
            if ($username && $username != '') {
                $guard_user = sfGuardUserTable::getInstance()->findOneBy('username', $username);
                if ($guard_user && !$guard_user->getIsSuperAdmin()) {
                    $md5_key = md5(time() . $username);
                    $updated_at = date('Y-m-d H:i:s');
                    $guard_user->setMd5Key($md5_key);
                    $guard_user->setUpdatedAt($updated_at);
                    $guard_user->save();


                    /** there should be a better way * */
                    sfApplicationConfiguration::getActive()->loadHelpers('Url');
                    $reset_pass_lnk = url_for('user/resetForgotten?token=' . $md5_key . '&timestamp=' . base64_encode($updated_at), true);

                    $translate_params = array(
                        '%name%' => $guard_user->getUserName(),
                        '%reset_pass_link%' => $reset_pass_lnk
                    );

                    $body = $this->getPartial("cms/email",array("message"=>"please click on the link to reset your password:" ,"link"=> $reset_pass_lnk));
                    $message = $this->getMailer()->compose(array("info@doseyeh.com"=>"Doseyeh.com"), $guard_user->getEmailAddress(), 'Reset Password', $body)->setContentType("text/html");

                    $this->getMailer()->send($message);
                    $this->redirect('message', array("message" => "Please check your email to proceed with reset password process"));
                } else {
                    $this->error = 'Username provided does not exist!';
                }
            } else {
                $this->error = 'Username Required Field!';
            }
        }
        $this->setLayout("login");
    }

    public function executeResetForgotten($request) {

        $this->message2 = $request->getParameter('message', false);
        $this->form2 = new sfGuardFormSignin();
        $this->token = $this->getRequestParameter('token');
        $this->timestamp = $this->getRequestParameter('timestamp');
        $this->forward404If(empty($this->token));

        $this->user = sfGuardUserTable::getInstance()->findOneBy('md5_key', $this->token);
        $this->forward404Unless($this->user);

        if (strtotime(base64_decode($this->timestamp)) + 3 * 24 * 60 * 60 < time()) { // expire the token after 3 days...
            $this->forward404('Token has been expired');
        }

        $this->form = new changePasswordForm();
        unset($this->form['oldpassword']);

        if ($request->isMethod('POST')) {
            $data = $this->getRequestParameter($this->form->getName());

            $this->form->bind($data);
            if ($this->form->isValid()) {
                $this->setNewPassword($data['newpassword'], $this->user);
                $this->redirect('success_message', array("message" => "your password was reset successfully!"));
            }
        }

        $this->setLayout("login");
    }

    protected function setNewPassword($new_password, $user) {
        $user->setPassword($new_password);
        $user->setMd5Key(null);
        $user->save();
    }

}